package admin

import (
	"fmt"
	"yunj/pkg/yunj/app/service/admin/adminservice"
	"yunj/pkg/yunj/app/service/admin/authservice"
	"yunj/pkg/yunj/app/service/admin/memberservice"
	errcodeEnum "yunj/pkg/yunj/core/enum/errcode"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

// 权限中间件
func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 校验用户是否登录
		adminMember := memberservice.Login.Verify(ctx)
		if ok := adminservice.SetLoginMember(ctx, adminMember); !ok {
			// 未登录
			if util.IsAsync(ctx) {
				response.FailErrcode(ctx, errcodeEnum.OVERDUE)
			} else {
				util.RedirectAdminTips(ctx, errcodeEnum.OVERDUE)
			}
			ctx.Abort()
			return
		}
		// fmt.Printf("当前登录成员：%v=>%v=>%v\r\n", adminMember.Id, adminMember.Username, adminMember.Name)

		// 获取当前请求权限、判断当前登录用户是否拥有权限
		adminAuth, err := authservice.Auth.GetRequestAuth(ctx)
		if err != nil {
			fmt.Printf("获取当前请求权限异常！%v\r\n", err)
			ctx.Next()
			return
		}
		// fmt.Printf("当前请求权限匹配：%v|%v|%v|%v\r\n", ctx.Request.RequestURI, ctx.Request.Method, adminAuth, err)
		if ok := adminservice.SetRequestAuth(ctx, adminAuth); !ok {
			// 未获取到当前请求权限
			ctx.Next()
			return
		}
		// fmt.Printf("当前请求权限：%v=>%v\r\n", adminAuth.Key, adminAuth.FullName)
		// 判断登录用户是否拥有权限
		if ok := adminservice.CheckAuth(ctx, adminAuth.Key); !ok {
			// 无权限
			if util.IsAsync(ctx) {
				response.FailErrcode(ctx, errcodeEnum.NO_AUTH)
			} else {
				util.RedirectAdminTips(ctx, errcodeEnum.NO_AUTH)
			}
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}
